import ErrorHandler from './ErrorHandler';
const TokenName = 'access_token';

export default function inject(request, location) {
  request.interceptors.request.use(
    config => {
      const token = global.access_token;
      if (token && !config.headers.withoutToken) {
        const url = config.url;
        let tokenUrl = '';
        if (url.indexOf('?') !== -1) {
          tokenUrl = `${url}&${TokenName}=${
            config.token ? config.token : token
          }`;
        } else {
          tokenUrl = `${url}?${TokenName}=${
            config.token ? config.token : token
          }`;
        }
        config.url = tokenUrl;
      }
      return config;
    },
    error => {
      // Toast.info('请求错误 ==>' + error.message);
      return Promise.reject(error);
    }
  );

  request.interceptors.response.use(
    response => {
      const data = response.data;
      if (data.code === 24001 && data.details) {
        let errors = Object.keys(data.details);
        if (errors.length) {
          data.message = data.details[errors[0]];
        }
      }
      return response.data;
    },
    error => {
      // Toast.info('返回错误 ==>' + error.message);
      ErrorHandler.handleHttpError({ ...error });
      return Promise.reject(error);
    }
  );
}
